<template>
  <div class="container dashboard-container">
    <div class="card dashboard-card">
      <h1 class="dashboard-title">DevOps 测试平台</h1>
      <button @click="handleLogout" class="btn logout-btn">退出登录</button>

      <div class="test-buttons">
        <button class="test-btn" @click="testMySQL" :disabled="loading">
          <span class="icon">🐬</span><span class="label">MySQL 数据库测试</span>
        </button>
        <button class="test-btn" @click="testRedis" :disabled="loading">
          <span class="icon">🔴</span><span class="label">Redis 测试</span>
        </button>
        <button class="test-btn" @click="testElasticsearch" :disabled="loading">
          <span class="icon">🔍</span><span class="label">Elasticsearch 测试</span>
        </button>
      </div>

      <div v-if="testResult" class="test-result" :class="testResult.type">
        <h3>{{ testResult.title }}</h3>
        <pre>{{ testResult.message }}</pre>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

export default {
  name: 'Dashboard',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const testResult = ref(null)

    const handleLogout = () => {
      localStorage.removeItem('isAuthenticated')
      localStorage.removeItem('user')
      router.push('/')
    }

    const showResult = (type, title, message) => {
      testResult.value = { type, title, message }
    }

    const testRedis = async () => {
      // 每次点击测试时刷新背景图
      window.dispatchEvent(new Event('app:refresh-background'))
      loading.value = true
      try {
        const redisResp = await axios.get('/api/test/redis')
        const redisBody = redisResp.data
        if (!(redisBody?.success && redisBody?.data)) {
          showResult('error', 'Redis 测试失败', redisBody?.message || '未知错误')
          return
        }

        const { metric, value, source, durationMs: redisDuration, ttlSeconds } = redisBody.data

        let mysqlDurationInfo = ''
        try {
          const mysqlResp = await axios.get('/api/test/mysql')
          const mysqlBody = mysqlResp.data
          if (mysqlBody?.success && mysqlBody?.data) {
            const { durationMs: mysqlDuration } = mysqlBody.data
            const diff = mysqlDuration - redisDuration
            const faster = diff > 0
            const diffAbs = Math.abs(diff)
            mysqlDurationInfo = [
              `数据库查询耗时: ${mysqlDuration} ms`,
              `缓存查询耗时: ${redisDuration} ms`,
              `${faster ? '本次查询比直接查数据库快' : '本次查询比直接查数据库慢'}: ${diffAbs} ms`
            ].join('\n')
          } else {
            mysqlDurationInfo = `数据库基准查询失败: ${mysqlBody?.message || '未知错误'}`
          }
        } catch (e) {
          mysqlDurationInfo = `数据库基准查询失败: ${e.response?.data?.message || e.message}`
        }

        const lines = [
          `指标: ${metric}`,
          `库中共有用户: ${value}`,
          `来源: ${source === 'redis' ? 'Redis 缓存' : '数据库'}`
        ]
        if (source === 'redis' && ttlSeconds !== undefined && ttlSeconds !== null) {
          lines.push(`剩余 TTL: ${ttlSeconds} s`)
        }
        if (mysqlDurationInfo) {
          lines.push('', mysqlDurationInfo)
        }
        showResult('success', 'Redis 测试成功', lines.join('\n'))
      } catch (error) {
        showResult('error', 'Redis 测试失败', error.response?.data?.message || error.message)
      } finally {
        loading.value = false
      }
    }

    const testMySQL = async () => {
      window.dispatchEvent(new Event('app:refresh-background'))
      loading.value = true
      try {
        const response = await axios.get('/api/test/mysql')
        const body = response.data
        if (body?.success && body?.data) {
          const { metric, value, source, durationMs } = body.data
          const lines = [
            `指标: ${metric}`,
            `库中共有用户: ${value}`,
            `来源: ${source}`,
            `耗时: ${durationMs} ms`
          ]
          showResult('success', 'MySQL 测试成功', lines.join('\n'))
        } else {
          showResult('error', 'MySQL 测试失败', body?.message || '未知错误')
        }
      } catch (error) {
        showResult('error', 'MySQL 测试失败', error.response?.data?.message || error.message)
      } finally {
        loading.value = false
      }
    }

    const testElasticsearch = async () => {
      window.dispatchEvent(new Event('app:refresh-background'))
      loading.value = true
      try {
        const response = await axios.get('/api/test/elasticsearch')
        const body = response.data
        if (body?.success && body?.data) {
          const { clusterName, status, version } = body.data
          const lines = [
            `集群: ${clusterName}`,
            `状态: ${status}`,
            `版本: ${version}`
          ]
          showResult('success', 'Elasticsearch 测试成功', lines.join('\n'))
        } else {
          showResult('error', 'Elasticsearch 测试失败', body?.message || '未知错误')
        }
      } catch (error) {
        showResult('error', 'Elasticsearch 测试失败', error.response?.data?.message || error.message)
      } finally {
        loading.value = false
      }
    }

    return {
      loading,
      testResult,
      handleLogout,
      testRedis,
      testMySQL,
      testElasticsearch
    }
  }
}
</script>

<style scoped>
.test-result {
  margin-top: 24px;
  padding: 16px;
  border-radius: 8px;
  border: 2px solid;
}

.test-result.success {
  background: #d4edda;
  border-color: #c3e6cb;
  color: #155724;
}

.test-result.error {
  background: #f8d7da;
  border-color: #f5c6cb;
  color: #721c24;
}

.test-result h3 {
  margin-bottom: 8px;
  font-size: 1.1rem;
}

.test-result pre {
  background: rgba(0, 0, 0, 0.06);
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.4;
}

.dashboard-title {
  margin: 0;
}

</style>
